package com.liyao.windowtest4.Utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * @program: windowtest4
 * @description:
 * @author: liu yan
 * @create: 2024-10-30 18:26
 */
public class SendWorkTasksUtils2 {
    private String sn;
    private String jobID;
    private String host;
    private int port;
    private boolean loop=false;
    private String RoutineName;

    private boolean state=false;

    public boolean isReturnState() {
        return returnState;
    }

    private boolean returnState;

    private JSONArray jobContent;

    private SocketClientUtil scu;

    private SocketClientUtil scul;

    private boolean ControlCycle;

    public SendWorkTasksUtils2(String sn) throws IOException {
        this.sn = sn;
        this.scu=null;
        this.scul=null;
        this.ControlCycle=true;

        //先获取重要参数
        ReadTxt(sn);

    }


    /**
     * 第一步：根据SN码获取扳手的host和port
     * 第二步：获取job的list
     * 第三步：获取任务是否无限循环
     *
     * */
    public void ReadTxt(String sn){

        //获取扳手的host、port
        try (BufferedReader br = new BufferedReader(new FileReader("src/main/resources/torqueItems.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if(line.contains("\"SN\":\"" + sn + "\"")){
                    JSONObject js= JSONObject.fromObject(line);
                    this.host=js.getString("Host");
                    this.port=js.getInt("Port");
                    System.out.println("地址："+host+",端口号："+port);
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("获取Host和Port失败");
            e.printStackTrace();
        }

        //获取任务是否无限循环
        try (BufferedReader br = new BufferedReader(new FileReader("src/main/resources/taskItems.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if(line.contains("\"SN\":\"" + sn + "\"")){
                    this.loop=true;
                    JSONObject js=JSONObject.fromObject(line);
                    this.jobID=js.getString("RoutineId");
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("获取是否循环失败");
            e.printStackTrace();
        }

        //获取job的list
        try (BufferedReader br = new BufferedReader(new FileReader("src/main/resources/Routine.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if(line.contains("\"code\":\"" + this.jobID + "\"")){
                    JSONObject js= JSONObject.fromObject(line);
                    this.RoutineName=js.getString("RoutineName");
                    this.jobContent=JSONArray.fromObject(js.getString("content"));
                    System.out.println("程序名称："+RoutineName+",任务详情："+jobContent);
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("获取job失败");
            e.printStackTrace();
        }
    }

    public void sentTasks() throws IOException, InterruptedException {
        //下发任务
        if(loop){
            //如果loop为true即：无限循环
            while (ControlCycle){
                System.out.println("循环开始：");
                //循环发送list中的单项任务
                for (int i = 0; i < this.jobContent.size(); i++) {
                    //下发任务给扳手
                    this.scu=new SocketClientUtil(this.host,this.port);
                    try{
                        // 建立扳手的连接
                        this.scu.connect();

                        // 发送消息到服务器
                        this.scu.sendMessage("RSSP;02;"+this.sn+";01;1;"+this.RoutineName+";0;2;34;34;35;36;0;0;0;0;1;1;0;1;0;0;\r\n");
                        // 从服务器接收消息
                        String response = this.scu.receiveMessage();
                        System.out.println("Server response: " + response);

                        // 假设连接成功
//                        updateMessage("下发成功");
                        this.scu.close();
//                        cancelled=true;
                        this.returnState=true;

                    } catch (IOException ex) {
                        System.out.println("扳手连接失败ss："+ex);
                        this.returnState=false;
                        if (this.scu != null) {
                            this.scu.close();
                        }
                        this.scu = null;
                        this.ControlCycle=false;
                        break;
                    }

                    //循环询问扳手是否有任务上传
                    if(returnState){
                        boolean a=true;
                        while (a){
                            try{
                                // 建立扳手的连接
                                this.scu.connect();

                                // 发送消息到服务器
                                this.scu.sendMessage("RSTS;1;"+this.sn+";1;\r\n");
                                // 从服务器接收消息
                                String response = this.scu.receiveMessage();
                                System.out.println("Server response: " + response);
                                if(response.split(";")[7].equals("1")){
                                    this.state=true;
                                }else{
                                    this.state=false;
                                    Thread.sleep(1000);
                                }

                                // 假设连接成功
                                //                        updateMessage("下发成功");
                                this.scu.close();
                                //                        cancelled=true;

                            } catch (IOException ex) {
                                System.out.println("扳手连接失败："+ex);
                            }

                            //如果state==true说明有数据要上传，获取要上传的数据
                            if(state){
                                try{
                                    // 建立扳手的连接
                                    this.scu.connect();

                                    // 发送消息到服务器
                                    this.scu.sendMessage("RSTD;01;"+this.sn+";01;\r\n");
                                    // 从服务器接收消息
                                    String response = this.scu.receiveMessage();
                                    System.out.println("Server response: " + response);
                                    //验证PsetID鱼PsetName是否对应，如果不对应不跳出循环，接着询问
                                    if(response.split(";")[2].equals(this.sn) && response.split(";")[11].equals("1") && response.split(";")[12].equals(this.RoutineName)){
                                        a=false;//跳出循环
                                        System.out.println("跳出循环");
                                    }else{
                                        a=true;
                                        System.out.println("继续循环");
                                    }
                                    //判断扭矩是否合格，不合格重新发送的逻辑

                                    //插入到文本中
                                    //假设加入成功
                                    returnState=true;


                                    // 假设连接成功
                                    //                        updateMessage("下发成功");
                                    this.scu.close();
                                    //                        cancelled=true;

                                } catch (IOException ex) {
                                    System.out.println("扳手连接失败："+ex);
                                }
                            }

                        }
                    }
                }
            }
        }else{
            //如果不是循环任务，则走这一步
            System.out.println("非循环步骤");
        }
    }

    public void closeSocket() throws IOException {
        System.out.println("停止socket连接");
        this.scu.close();
        this.scu=null;
    }

    public void sendTaskForInit() throws IOException {
        this.scul=new SocketClientUtil(this.host,this.port);
        try{
            // 建立扳手的连接
            this.scul.connect();

            // 发送消息到服务器
            this.scul.sendMessage("RSTS;01;"+this.sn+";01;\r\n");
            // 从服务器接收消息
            String response = scul.receiveMessage();
            System.out.println("Server response: " + response);

//            if(response.split(";")[5].equals(0)){
//                this.returnState= false;
//            }else{
                this.returnState= true;
//            }
            // 假设连接成功
            this.scul.close();

        } catch (IOException ex) {
            System.out.println("扳手连接失败sss："+ex);
            this.returnState=false;
            if (this.scul != null) {
                this.scul.close();
            }
            this.ControlCycle=false;
        }
    }
}
